<template>
  <div class="header-container">
    <n-flex justify="space-between" align="center" class="header-bar">
      <!-- 左侧 Logo -->
      <div class="logo">
        <n-icon size="28">
          <img src="/健身器械.svg" alt="器械通 Logo" class="logo-image"/>
        </n-icon>
        <span class="site-name">"器械通"健身一站式服务平台</span>
      </div>      <!-- 中间导航菜单 -->
      <n-flex align="center" justify="center" class="nav-menu">
        <n-space size="large">
          <n-button text @click="router.push('/')">
            <template #icon>
              <n-icon><HomeOutline /></n-icon>
            </template>
            健身器械
          </n-button>
          <n-button text @click="router.push('/course')">
            <template #icon>
              <n-icon><Barbell /></n-icon>
            </template>
            动作课程
          </n-button>
          <n-button text @click="router.push('/trade')">
            <template #icon>
              <n-icon><CartOutline /></n-icon>
            </template>
            器械交易
          </n-button>
          <n-button text @click="router.push('/map')">
            <template #icon>
              <n-icon><LocationOutline /></n-icon>
            </template>
            附近场馆
          </n-button>          <n-button text @click="router.push('/gym')">
            <template #icon>
              <n-icon><BusinessOutline /></n-icon>
            </template>
            场馆详情
          </n-button>
          <n-button text @click="router.push('/activity/promotion')" type="warning">
            <template #icon>
              <n-icon><GiftOutline /></n-icon>
            </template>
            活动推广
          </n-button>
        </n-space>
      </n-flex>

      <!-- 右侧用户菜单 -->
      <n-flex align="center" class="user-actions">
        <template v-if="!userInfo?.tokenInfo?.isLogin">
          <n-button text @click="router.push('/login?tab=signin')">登录</n-button>
          <n-button text @click="router.push('/login?tab=signup')">注册</n-button>
        </template>
        <template v-else>
          <!-- 添加发布器械按钮 -->
          <n-button
            v-if="route.path === '/' && userInfo?.role === 2"
            type="primary"
            @click="showPublishModal = true"
            class="publish-btn"
          >
            <template #icon>
              <n-icon><AddCircleOutline /></n-icon>
            </template>
            发布器械
          </n-button>          <!-- 添加发布课程按钮 -->
          <n-button
            v-if="route.path === '/course' && userInfo?.role === 2"
            type="primary"
            @click="showPublishCourseModal = true"
            class="publish-btn"
          >
            <template #icon>
              <n-icon><AddCircleOutline /></n-icon>
            </template>
            发布课程
          </n-button>          <!-- 添加上架器械按钮 -->
          <n-button
            v-if="route.path === '/trade'"
            type="primary"
            @click="openEquipmentListModal"
            class="publish-btn"
          >
            <template #icon>
              <n-icon><Add /></n-icon>
            </template>
            上架器械
          </n-button>

          <n-popover trigger="hover" placement="bottom">
            <template #trigger>
              <n-avatar
                  round
                  size="medium"
                  :src="userInfo.avatarImgUrl ? BASE_URL + userInfo.avatarImgUrl : '/default_avatar.svg'"
                  class="cursor-pointer"
              />
            </template>
            <!-- 弹出的用户信息卡片 -->
            <div class="user-popover">
              <n-space vertical :size="16">
                <!-- 用户基本信息和角色信息 -->
                <n-space vertical :size="8">
                  <n-flex align="center" class="user-info">
                    <n-avatar
                        round
                        size="small"
                        :src="userInfo.avatarImgUrl ? BASE_URL + userInfo.avatarImgUrl : '/default_avatar.svg'"
                    />
                    <span class="nickname">{{ userInfo.nickname }}</span>
                  </n-flex>
                  
                  <n-flex align="center" class="role-info">
                    <n-image
                      :src="getRoleIcon(userInfo.role)"
                      width="20"
                      preview-disabled
                      class="role-icon"
                    />
                    <span class="role-text">{{ getRoleName(userInfo.role) }}</span>
                  </n-flex>
                </n-space>

                <n-divider />
                  <!-- 操作按钮 -->
                <n-flex vertical class="user-links">                  <n-button text @click="router.push('/user/center')">
                    <template #icon>
                      <n-icon><PersonOutline/></n-icon>
                    </template>
                    个人中心
                  </n-button>
                  <n-button text @click="logout">
                    <template #icon>
                      <n-icon><LogOutOutline/></n-icon>
                    </template>
                    退出登录
                  </n-button>
                </n-flex>
              </n-space>
            </div>
          </n-popover>          <!-- 消息按钮 -->
          <n-badge :value="unreadCount" :max="99" :show="unreadCount > 0">
            <n-button text @click="router.push('/chat')">
              <template #icon>
                <n-icon><NotificationsOutline /></n-icon>
              </template>
              消息
            </n-button>
          </n-badge>
        </template>
      </n-flex>
    </n-flex>

    <!-- 发布器械弹窗 -->
    <n-modal v-model:show="showPublishModal" preset="card" style="width: 600px">
      <n-card title="发布器械">
        <n-form
          ref="publishFormRef"
          :model="publishForm"
          :rules="publishRules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="器械图片" path="coverImg">
            <n-upload
              accept="image/*"
              :max="1"
              :default-file-list="coverImgList"
              @change="handleCoverChange"
              :custom-request="handleCoverUpload"
              @remove="handleCoverRemove"
              list-type="image-card"
            >
              点击或拖动图片到此处
            </n-upload>
          </n-form-item>

          <n-form-item label="器械名称" path="title">
            <n-input v-model:value="publishForm.title" placeholder="请输入器械标准名称"/>
          </n-form-item>

          <n-form-item label="锻炼部位" path="bodyPart">
            <n-select
              v-model:value="publishForm.bodyPart"
              :options="bodyPartOptions"
              placeholder="请选择主要锻炼部位"
            />
          </n-form-item>

          <n-form-item label="使用指导" path="usageGuide">
            <n-input
              v-model:value="publishForm.usageGuide"
              type="textarea"
              placeholder="请输入器械使用指导说明"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>

          <n-form-item label="注意事项" path="precautions">
            <n-input
              v-model:value="publishForm.precautions"
              type="textarea"
              placeholder="请输入安全注意事项"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>

          <n-space justify="end">
            <n-button @click="showPublishModal = false">取消</n-button>
            <n-button type="primary" @click="handlePublish" :loading="publishing">
              发布
            </n-button>
          </n-space>
        </n-form>
      </n-card>
    </n-modal>    <!-- 发布课程弹窗 -->
    <n-modal v-model:show="showPublishCourseModal" preset="card" style="width: 600px">
      <n-card title="发布课程">
        <n-form
          ref="publishCourseFormRef"
          :model="publishCourseForm"
          :rules="publishCourseRules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
        >
          <n-form-item label="课程视频" path="videoUrl">
            <n-upload
              accept="video/*"
              :max="1"
              :default-file-list="courseVideoList"
              @change="handleVideoChange"
              :custom-request="handleVideoUpload"
              @remove="handleVideoRemove"
              list-type="image-card"
            >
              点击或拖动视频到此处
            </n-upload>
          </n-form-item>

          <n-form-item label="课程封面" path="coverImg">
            <n-upload
              accept="image/*"
              :max="1"
              :default-file-list="courseCoverList"
              @change="handleCourseCoverChange"
              :custom-request="handleCourseCoverUpload"
              @remove="handleCourseCoverRemove"
              list-type="image-card"
            >
              点击或拖动图片到此处
            </n-upload>
          </n-form-item>

          <n-form-item label="课程名称" path="title">
            <n-input v-model:value="publishCourseForm.title" placeholder="请输入课程名称"/>
          </n-form-item>

          <n-form-item label="使用器械" path="equipmentName">
            <n-input v-model:value="publishCourseForm.equipmentName" placeholder="请输入使用的器械名称"/>
          </n-form-item>

          <n-form-item label="动作要领" path="description">
            <n-input
              v-model:value="publishCourseForm.description"
              type="textarea"
              placeholder="请输入动作要领说明"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>

          <n-space justify="end">
            <n-button @click="showPublishCourseModal = false">取消</n-button>
            <n-button type="primary" @click="handlePublishCourse" :loading="publishingCourse">
              发布
            </n-button>
          </n-space>
        </n-form>
      </n-card>
    </n-modal>    <!-- 上架器械弹窗 -->
    <n-modal 
      v-model:show="showEquipmentListModal" 
      preset="card" 
      style="width: 620px; max-height: 85vh"
      :auto-focus="false"
      :mask-closable="false"
    >
      <n-card :title="equipmentListTitle">
        <n-scrollbar style="max-height: 70vh">
          <n-form
            ref="equipmentListFormRef"
            :model="equipmentListForm"
            :rules="equipmentListRules"
            label-placement="left"
            label-width="90"
            require-mark-placement="right-hanging"
          ><n-form-item label="器械图片" path="images">            <n-upload
              accept="image/*"
              :max="5"
              multiple
              v-model:file-list="equipmentImageList"
              @change="handleEquipmentImageChange"
              :custom-request="handleEquipmentImageUpload"
              @remove="handleEquipmentImageRemove"
              list-type="image-card"
              :show-file-list="true"
            >
              <n-upload-dragger>
                <div style="margin-bottom: 8px">
                  <n-icon size="32" :depth="3">
                    <Add />
                  </n-icon>
                </div>
                <n-text style="font-size: 14px">
                  点击或拖拽上传
                </n-text>
                <n-p depth="3" style="margin: 4px 0 0 0; font-size: 12px">
                  支持1-5张图片
                </n-p>
              </n-upload-dragger>
            </n-upload>            <!-- 图片计数器 -->
            <n-text depth="3" style="font-size: 12px; margin-top: 4px">
              已上传 {{ uploadedImageCount }} 张图片
            </n-text>
          </n-form-item>

          <n-form-item label="器械类型" path="equipmentType">
            <n-select
              v-model:value="equipmentListForm.equipmentType"
              :options="equipmentTypeOptions"
              placeholder="请选择器械类型"
            />
          </n-form-item>

          <n-form-item label="器械名称" path="name">
            <n-input v-model:value="equipmentListForm.name" placeholder="请输入器械名称"/>
          </n-form-item>

          <n-form-item label="价格" path="price">
            <n-input-number 
              v-model:value="equipmentListForm.price" 
              placeholder="请输入价格"
              :min="0.01"
              :max="999999"
              :precision="2"
              style="width: 100%"
              :parse="(input) => {
                const cleaned = input.replace(/[^\d.]/g, '');
                return cleaned === '' ? null : Number(cleaned);
              }"
              :format="(value) => value === null ? '' : String(value)"
            >
              <template #suffix>
                元
              </template>
            </n-input-number>          </n-form-item>

          <n-form-item v-if="equipmentListForm.equipmentType === 'USED'" label="成色等级" path="condition">
            <n-select
              v-model:value="equipmentListForm.condition"
              :options="conditionOptions"
              placeholder="请选择器械成色等级"
            />
          </n-form-item>

          <n-form-item label="器械描述" path="description">
            <n-input
              v-model:value="equipmentListForm.description"
              type="textarea"
              placeholder="请详细描述器械的特点、功能等信息"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </n-form-item>          <n-space justify="end">
            <n-button @click="showEquipmentListModal = false">取消</n-button>
            <n-button type="primary" @click="handleEquipmentList" :loading="listingEquipment">
              上架
            </n-button>
          </n-space>
        </n-form>
        </n-scrollbar>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useMessage } from 'naive-ui';
import http from '../utils/http.js';
import qs from 'qs';
import { 
  PersonOutline, 
  LogOutOutline, 
  WalletOutline, 
  GiftOutline,
  HomeOutline,
  CartOutline,
  LocationOutline,  NotificationsOutline,
  AddCircleOutline,
  Add,
  Barbell, // 添加健身器械图标
  BusinessOutline, // 添加场馆详情图标
  CalendarOutline // 添加日历图标
} from '@vicons/ionicons5'

const router = useRouter();
const route = useRoute();
const message = useMessage();
const userInfo = ref(getUser());
const BASE_URL = window.BASE_URL;

// 消息相关数据
const unreadCount = ref(0);

// 获取未读消息数量
const getUnreadMessageCount = async () => {
  if (!userInfo.value?.tokenInfo?.isLogin) return;
  
  try {
    const response = await http.get(BASE_URL + '/v1/chat/unread-count');
    if (response.data.code === 2000) {
      unreadCount.value = response.data.data;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 发布器械相关数据
const showPublishModal = ref(false)
const publishFormRef = ref(null)
const publishing = ref(false)
const coverImgList = ref([])

const publishForm = ref({
  title: '',
  bodyPart: null,
  usageGuide: '',
  precautions: '',
  coverImg: ''
})

// 锻炼部位选项
const bodyPartOptions = [
  { label: '胸部', value: '胸部' },
  { label: '背部', value: '背部' },
  { label: '肩部', value: '肩部' },
  { label: '腿部', value: '腿部' },
  { label: '手臂', value: '手臂' },
  { label: '多功能', value: '多功能' }
]

const publishRules = {
  title: { required: true, message: '请输入器械名称', trigger: ['blur', 'input'] },
  bodyPart: { required: true, message: '请选择锻炼部位', trigger: ['blur', 'change'] },
  usageGuide: { required: true, message: '请输入使用指导说明', trigger: ['blur', 'input'] },
  coverImg: { required: true, message: '请上传器械图片', trigger: ['blur', 'change'] }
}

// 图片上传相关方法
const handleCoverUpload = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  
  return http.post(BASE_URL+'/v1/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    if (response.data.code === 2000) {
      publishForm.value.coverImg = response.data.data
      message.success('图片上传成功')
    }
  }).catch(error => {
    console.error('图片上传失败:', error)
    message.error('图片上传失败，请稍后重试')
  })
}

const handleCoverChange = (options) => {
  const { file } = options
  if (file.status === 'finished') {
    coverImgList.value = [{
      id: 'cover',
      name: file.name,
      status: 'finished',
      url: file.url
    }]
  }
}

const handleCoverRemove = () => {
  if (publishForm.value.coverImg) {
    http.post(BASE_URL+'/v1/file/remove', qs.stringify({
      imgUrl: publishForm.value.coverImg
    })).then(response => {
      if (response.data.code === 2000) {
        publishForm.value.coverImg = ''
        coverImgList.value = []
        message.success('图片已删除')
      }
    }).catch(error => {
      console.error('图片删除失败:', error)
      message.error('图片删除失败，请稍后重试')
    })
  }
}

// 发布器械
const handlePublish = () => {
  publishFormRef.value?.validate(async (errors) => {
    if (!errors) {
      publishing.value = true
      try {
        const userId = userInfo.value.tokenInfo.loginId
        console.log('当前用户ID:', userId)
        // 获取教练信息
        const coachResponse = await http.get(`${BASE_URL}/v1/coach/selectByUserId`, {
          params: {
            userId: userId
          }
        })
        
        console.log('查到的教练信息数据:', coachResponse.data.data)
        
        if (coachResponse.data.code !== 2000) {
          throw new Error('获取教练信息失败')
        }

        if (!coachResponse.data.data?.coachId) {
          throw new Error('教练ID不存在')
        }

        const coachId = coachResponse.data.data.coachId 
        console.log('教练ID:', coachId)
        
        const formData = qs.stringify({
          coachId: coachId,
          title: publishForm.value.title,
          bodyPart: publishForm.value.bodyPart,
          usageGuide: publishForm.value.usageGuide,
          precautions: publishForm.value.precautions,
          coverImg: publishForm.value.coverImg
        })
          const response = await http.post(BASE_URL+'/v1/card/insert', formData)
        if (response.data.code === 2000) {
          message.success('发布成功')
          showPublishModal.value = false
          // 重置表单
          publishForm.value = {
            title: '',
            bodyPart: null,
            usageGuide: '',
            precautions: '',
            coverImg: ''
          }
          coverImgList.value = []
          window.location.reload() // 刷新页面以更新列表
        } else {
          throw new Error(response.data.msg || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        message.error(error.message || '发布失败，请稍后重试')
      } finally {
        publishing.value = false
      }
    } else {
      message.error('请检查表单填写是否正确')
    }
  })
}

// 发布课程相关数据
const showPublishCourseModal = ref(false)
const publishCourseFormRef = ref(null)
const publishingCourse = ref(false)
const courseVideoList = ref([])
const courseCoverList = ref([])

const publishCourseForm = ref({
  title: '',
  equipmentName: '',
  description: '',
  coverImg: '',
  videoUrl: '',
  coachId: null  
})

const publishCourseRules = {
  title: { required: true, message: '请输入课程名称', trigger: ['blur', 'input'] },
  equipmentName: { required: true, message: '请输入使用的器械名称', trigger: ['blur', 'change'] },
  description: { required: true, message: '请输入动作要领说明', trigger: ['blur', 'input'] },
  coverImg: { required: true, message: '请上传课程封面', trigger: ['blur', 'change'] },
  videoUrl: { required: true, message: '请上传课程视频', trigger: ['blur', 'change'] }
}

// 上架器械相关数据
const showEquipmentListModal = ref(false)
const equipmentListFormRef = ref(null)
const listingEquipment = ref(false)
const equipmentImageList = ref([])

const equipmentListForm = ref({
  name: '',
  price: null,
  equipmentType: 'NEW', // 默认选择新品器械
  condition: null,
  description: '',
  images: []
})

// 计算属性：上传的图片数量
const uploadedImageCount = computed(() => {
  return equipmentListForm.value.images.length
})

// 器械类型选项
const equipmentTypeOptions = [
  { label: '新品器械', value: 'NEW' },
  { label: '二手器械', value: 'USED' }
]

// 成色等级选项
const conditionOptions = [
  { label: '九九新', value: '九九新' },
  { label: '九成新', value: '九成新' },
  { label: '八成新', value: '八成新' },
  { label: '七成新', value: '七成新' },
  { label: '六成新及以下', value: '六成新及以下' }
]

// 判断是否为商家
const isMerchant = computed(() => userInfo.value?.role === 3)

// 根据选择的器械类型生成弹窗标题
const equipmentListTitle = computed(() => {
  return equipmentListForm.value.equipmentType === 'NEW' ? '上架新品器械' : '上架二手器械'
})

// 上架器械表单验证规则
const equipmentListRules = computed(() => {
  const baseRules = {
    name: { required: true, message: '请输入器械名称', trigger: ['blur', 'input'] },
    price: { 
      required: true, 
      message: '请输入价格', 
      trigger: ['blur', 'change'],
      type: 'number',
      validator: (rule, value) => {
        if (value === null || value === undefined || value === '') {
          return new Error('请输入价格')
        }
        const numValue = Number(value)
        if (isNaN(numValue)) {
          return new Error('请输入有效的价格')
        }
        if (numValue < 0.01) {
          return new Error('价格不能低于0.01元')
        }
        if (numValue > 999999) {
          return new Error('价格不能超过999999元')
        }
        return true
      }
    },
    equipmentType: { required: true, message: '请选择器械类型', trigger: ['blur', 'change'] },
    description: { required: true, message: '请输入器械描述', trigger: ['blur', 'input'] },
    images: { 
      required: true, 
      message: '请上传器械图片', 
      trigger: ['blur', 'change'],
      validator: (rule, value) => {
        if (!value || value.length === 0) {
          return new Error('请至少上传一张器械图片')
        }
        return true
      }
    }
  }
  
  // 如果选择了二手器械，需要选择成色等级
  if (equipmentListForm.value.equipmentType === 'USED') {
    baseRules.condition = { required: true, message: '请选择器械成色等级', trigger: ['blur', 'change'] }
  }
  
  return baseRules
})

// 课程视频上传相关方法
const handleVideoUpload = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  
  return http.post(BASE_URL+'/v1/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    if (response.data.code === 2000) {
      publishCourseForm.value.videoUrl = response.data.data
      message.success('视频上传成功')
    }
  }).catch(error => {
    console.error('视频上传失败:', error)
    message.error('视频上传失败，请稍后重试')
  })
}

const handleVideoChange = (options) => {
  const { file } = options
  if (file.status === 'finished') {
    courseVideoList.value = [{
      id: 'video',
      name: file.name,
      status: 'finished',
      url: file.url
    }]
  }
}

const handleVideoRemove = () => {
  if (publishCourseForm.value.videoUrl) {
    http.post(BASE_URL+'/v1/file/remove', qs.stringify({
      fileUrl: publishCourseForm.value.videoUrl
    })).then(response => {
      if (response.data.code === 2000) {
        publishCourseForm.value.videoUrl = ''
        courseVideoList.value = []
        message.success('视频已删除')
      }
    }).catch(error => {
      console.error('视频删除失败:', error)
      message.error('视频删除失败，请稍后重试')
    })
  }
}

// 发布课程
const handlePublishCourse = () => {
  publishCourseFormRef.value?.validate(async (errors) => {
    if (!errors) {
      publishingCourse.value = true
      try {
        const userId = userInfo.value.tokenInfo.loginId
        console.log('当前用户ID:', userId)
          // 获取教练信息
        const coachResponse = await http.get(`${BASE_URL}/v1/coach/selectByUserId`, {
          params: {
            userId: userId
          }
        })
        
        console.log('查到的教练信息数据:', coachResponse.data.data)
        
        if (coachResponse.data.code !== 2000) {
          throw new Error('获取教练信息失败')
        }

        if (!coachResponse.data.data?.coachId) {
          throw new Error('教练ID不存在')
        }

        const coachId = coachResponse.data.data.coachId 
        console.log('教练ID:', coachId)

        // 构造课程数据
        const courseData = {
          coachId: coachId,
          title: publishCourseForm.value.title,
          equipmentName: publishCourseForm.value.equipmentName,
          description: publishCourseForm.value.description,
          coverImg: publishCourseForm.value.coverImg,
          videoUrl: publishCourseForm.value.videoUrl
        }
          // 发布课程
        const formData = qs.stringify(courseData)
        const response = await http.post(BASE_URL+'/v1/course/insert', formData)
        
        if (response.data.code === 2000) {
          message.success('发布成功')
          showPublishCourseModal.value = false
          // 重置表单
          publishCourseForm.value = {
            title: '',
            equipmentName: '',
            description: '',
            coverImg: '',
            videoUrl: '',
            coachId: null
          }
          courseVideoList.value = []
          courseCoverList.value = []
          window.location.reload()
        } else {
          throw new Error(response.data.msg || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        message.error(error.message || '发布失败，请稍后重试')
      } finally {
        publishingCourse.value = false
      }
    } else {
      message.error('请检查表单填写是否正确')
    }
  })
}

// 课程封面上传相关方法
const handleCourseCoverUpload = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  
  return http.post(BASE_URL+'/v1/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    if (response.data.code === 2000) {
      publishCourseForm.value.coverImg = response.data.data
      message.success('封面上传成功')
    }
  }).catch(error => {
    console.error('封面上传失败:', error)
    message.error('封面上传失败，请稍后重试')
  })
}

const handleCourseCoverChange = (options) => {
  const { file } = options
  if (file.status === 'finished') {
    courseCoverList.value = [{
      id: 'cover',
      name: file.name,
      status: 'finished',
      url: file.url
    }]
  }
}

const handleCourseCoverRemove = () => {
  if (publishCourseForm.value.coverImg) {
    http.post(BASE_URL+'/v1/file/remove', qs.stringify({
      imgUrl: publishCourseForm.value.coverImg
    })).then(response => {
      if (response.data.code === 2000) {
        publishCourseForm.value.coverImg = ''
        courseCoverList.value = []
        message.success('封面已删除')
      }
    }).catch(error => {
      console.error('封面删除失败:', error)
      message.error('封面删除失败，请稍后重试')
    })
  }
}

// 打开上架器械模态框
const openEquipmentListModal = () => {
  // 重置表单数据
  equipmentListForm.value = {
    name: '',
    price: null,
    equipmentType: 'NEW',
    condition: null,
    description: '',
    images: []
  }
  
  // 重置图片列表
  equipmentImageList.value = []
  
  // 清除表单验证错误
  if (equipmentListFormRef.value) {
    equipmentListFormRef.value.restoreValidation()
  }
  
  // 显示模态框
  showEquipmentListModal.value = true
  
  console.log('打开设备上架模态框，表单已重置')
}

// 上架器械图片上传相关方法
const handleEquipmentImageUpload = ({ file, onFinish, onError }) => {
  const formData = new FormData()
  // 使用 trade API 的文件上传，参数名为 files
  formData.append('files', file.file)
  
  return http.post(BASE_URL + '/v1/trade/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    if (response.data.code === 2000) {
      // trade upload API 返回的是数组，取第一个
      const uploadedUrls = response.data.data
      const imageUrl = Array.isArray(uploadedUrls) ? uploadedUrls[0] : uploadedUrls
      
      message.success('图片上传成功')
        console.log('上传成功，图片URL:', imageUrl)
        // 关键：设置文件对象的 url 和 thumbnailUrl 属性（需要完整URL用于显示）
      const fullImageUrl = BASE_URL + imageUrl
      file.url = fullImageUrl
      file.thumbnailUrl = fullImageUrl
      file.status = 'finished'
      
      console.log('设置文件对象URL:', fullImageUrl)
      console.log('BASE_URL:', BASE_URL)
      console.log('原始imageUrl:', imageUrl)
      
      // 直接更新表单中的图片数组
      if (!equipmentListForm.value.images.includes(imageUrl)) {
        equipmentListForm.value.images.push(imageUrl)
      }
      
      console.log('上传完成后表单图片数组:', equipmentListForm.value.images)
      console.log('图片数量:', equipmentListForm.value.images.length)
      
      // 调用 onFinish 回调
      if (onFinish) {
        onFinish()
      }
    } else {
      message.error(response.data.msg || '图片上传失败')
      if (onError) {
        onError()
      }
      throw new Error(response.data.msg || '图片上传失败')
    }
  }).catch(error => {
    console.error('图片上传失败:', error)
    message.error('图片上传失败，请稍后重试')
    if (onError) {
      onError()
    }
    throw error
  })
}

const handleEquipmentImageChange = (options) => {
  const { fileList } = options
  console.log('图片列表变化:', fileList) // 调试日志
  
  // 更新图片列表状态
  equipmentImageList.value = fileList
  
  // 同步更新表单数据中的图片数组 - 只从已完成上传的文件中获取URL
  const finishedImages = fileList
    .filter(file => file.status === 'finished' && file.url)
    .map(file => file.url)
  
  console.log('提取的已完成图片URLs:', finishedImages) // 调试日志
  
  // 更新表单中的图片数组
  equipmentListForm.value.images = finishedImages
  
  console.log('更新后的表单图片数组:', equipmentListForm.value.images) // 调试日志
  console.log('图片数量:', equipmentListForm.value.images.length) // 调试日志
  
  // 检查是否有超过5张图片的警告
  if (fileList.length > 5) {
    message.warning('最多只能上传5张图片')
  }
}

const handleEquipmentImageRemove = (options) => {
  const { file } = options
  console.log('删除图片:', file) // 调试日志
  
  if (file.url) {
    // 从表单数据中移除对应的图片URL
    const imageIndex = equipmentListForm.value.images.findIndex(url => url === file.url)
    if (imageIndex > -1) {
      equipmentListForm.value.images.splice(imageIndex, 1)
      console.log('删除后图片数组:', equipmentListForm.value.images) // 调试日志
    }
      // 调用后端删除接口
    const deleteData = qs.stringify({
      'imgUrls[]': file.url  // 使用数组格式的参数名
    })
    
    http.post(BASE_URL + '/v1/trade/remove', deleteData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).then(response => {
      if (response.data.code === 2000) {
        message.success('图片已删除')
      } else {
        console.error('图片删除失败:', response.data.msg)
      }
    }).catch(error => {
      console.error('图片删除失败:', error)
    })
  }
  
  // 返回 true 允许删除
  return true
}

// 上架器械处理方法
const handleEquipmentList = () => {
  console.log('开始验证表单，当前图片数量:', equipmentListForm.value.images.length)
  console.log('当前图片数组:', equipmentListForm.value.images)
  console.log('当前器械类型:', equipmentListForm.value.equipmentType)
  console.log('当前价格:', equipmentListForm.value.price)
  
  equipmentListFormRef.value?.validate(async (errors) => {
    if (!errors) {
      // 双重检查图片数量
      if (!equipmentListForm.value.images || equipmentListForm.value.images.length === 0) {
        console.log('图片验证失败：图片数组为空')
        message.warning('请至少上传一张器械图片')
        return
      }
      
      // 检查器械类型
      if (!equipmentListForm.value.equipmentType) {
        console.log('器械类型验证失败：器械类型为空')
        message.warning('请选择器械类型')
        return
      }
      
      // 检查价格
      if (!equipmentListForm.value.price || equipmentListForm.value.price <= 0) {
        console.log('价格验证失败：价格无效')
        message.warning('请输入有效的价格')
        return
      }
      
      console.log('表单验证通过，开始提交')
      listingEquipment.value = true
      try {
        // 构造上架数据，使用 trade API
        const tradeData = {
          equipmentName: equipmentListForm.value.name,
          description: equipmentListForm.value.description,
          price: Number(equipmentListForm.value.price), // 确保价格为数字
          quantity: 1, // 默认数量为1
          equipmentType: equipmentListForm.value.equipmentType, // 确保器械类型不为空
          conditionLevel: equipmentListForm.value.equipmentType === 'USED' ? equipmentListForm.value.condition : null, // 成色等级
          images: equipmentListForm.value.images, // 图片数组
          merchantId: userInfo.value.userId, // 商家ID（对于个人用户，也使用userId作为merchantId）
          userId: userInfo.value.userId // 用户ID
        };
        
        console.log('上架器械数据:', tradeData)
        console.log('equipmentType值:', tradeData.equipmentType)
          // 调用后端 trade API
        const response = await http.post(BASE_URL + '/v1/trade/insert', tradeData, {
          headers: { 'Content-Type': 'application/json' }
        })
        
        if (response.data.code === 2000) {
          message.success(`${equipmentListForm.value.equipmentType === 'NEW' ? '新品器械' : '二手器械'}上架成功！`)
          showEquipmentListModal.value = false
          
          // 重置表单
          equipmentListForm.value = {
            name: '',
            price: null,
            equipmentType: 'NEW',
            condition: null,
            description: '',
            images: []
          }
          equipmentImageList.value = []
          
          // 清除表单验证状态
          if (equipmentListFormRef.value) {
            equipmentListFormRef.value.restoreValidation()
          }
          
          console.log('表单已重置，图片数量:', equipmentListForm.value.images.length)
          
          // 刷新页面以显示新上架的器械
          if (route.path === '/trade') {
            window.location.reload()
          }
        } else {
          message.error(response.data.msg || '上架失败')
        }
        
      } catch (error) {
        console.error('上架失败:', error)
        message.error(error.message || '上架失败，请稍后重试')
      } finally {
        listingEquipment.value = false
      }
    } else {
      console.log('表单验证失败:', errors)
      message.error('请检查表单填写是否正确')
    }
  })
}

// 教练身份判断
const isCoach = computed(() => userInfo.value?.role === 2)

// 添加事件监听器来更新用户信息
onMounted(() => {
  window.addEventListener('user-updated', () => {
    userInfo.value = getUser();
  });
  
  // 获取未读消息数量
  getUnreadMessageCount();
  
  // 定期刷新未读消息数量（每30秒）
  setInterval(() => {
    if (userInfo.value?.tokenInfo?.isLogin) {
      getUnreadMessageCount();
    }
  }, 30000);
});

const logout = async () => {
  try {
    const response = await http.post(BASE_URL+'/v1/user/logout');
    if (response.data.code === 2000) {
      message.success("退出登录成功");
      localStorage.removeItem('user');
      userInfo.value = null;
      await router.push('/login');
    } else {
      message.error("退出登录失败");
    }
  } catch (error) {
    console.error('退出登录失败:', error);
    message.error("退出登录失败，请稍后重试");
  }
};

const getRoleIcon = (role) => {
  switch(role) {
    case 1: return '/用户.svg';
    case 2: return '/健身教练.svg';
    case 3: return '/健身器械.svg';
    case 4: return '/健身场馆.svg';
    default: return '/用户.svg';
  }
}

const getRoleName = (role) => {
  switch(role) {
    case 1: return '健身爱好者';
    case 2: return '健身教练';
    case 3: return '器械商家';
    case 4: return '场馆人员';
    default: return '用户';
  }
}
</script>

<style scoped>
/* 头部容器样式 */
.header-container {
  position: relative;
  width: 100%;
}

/* 头部导航栏样式 */
.header-bar {
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

/* Logo区域样式 */
.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Logo图片样式 */
.logo-image {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

/* 站点名称样式 */
.site-name {
  margin-left: 4px;
  font-size: 16px;
  font-weight: bold;
  color: #212121;
}

/* 导航菜单样式 */
.nav-menu {
  flex: 1;
  justify-content: center;
  padding: 0 20px;
}

/* 导航菜单按钮样式 */
.nav-menu .n-button {
  font-size: 16px;
  padding: 0 16px;
}

/* 用户操作区域样式 */
.user-actions {
  gap: 10px;
}

/* 用户信息弹出框样式 */
.user-popover {
  width: 240px;
  padding: 16px;
}

.user-info {
  gap: 12px;
}

.username {
  font-size: 18px; /* 增大字体大小 */
  font-weight: 600;
  color: var(--n-text-color);
}

.role-info {
  gap: 8px;
  margin-left: 4px; /* 添加左边距，与头像对齐 */
}

.role-icon {
  width: 24px; /* 增大图标大小 */
  height: 24px; /* 增大图标大小 */
}

.role-text {
  font-size: 16px; /* 增大字体大小 */
  color: var(--n-text-color-3);
}

/* 用户链接列表样式 */
.user-links {
  gap: 8px;
}

/* 用户链接按钮样式 */
.user-links .n-button {
  justify-content: flex-start;
  width: 100%;
  padding: 8px;
}

/* 使活动按钮更醒目 */
:deep(.n-button.n-button--warning) {
  font-weight: 500;
}

:deep(.n-button.n-button--warning:hover) {
  background-color: rgba(250, 192, 0, 0.1);
}

/* 鼠标指针样式 */
.cursor-pointer {
  cursor: pointer;
}

/* 导航按钮图标样式优化 */
:deep(.n-button .n-icon) {
  margin-right: 4px;
  font-size: 18px;
}

/* 发布按钮样式 */
:deep(.n-button--primary) {
  margin-left: 16px;
}

/* 发布器械按钮样式 */
.publish-btn {
  margin-right: 24px; /* 增加与头像的间距 */
}
</style>
